package logic

import (
	"context"
	"errors"
	"house/cache"
	"house/models"

	"house/house"
	"house/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *house.LoginReq) (*house.LoginResp, error) {
	// todo:登录
	var err error
	var h models.User
	sms := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Account+"login").Val()
	if sms != in.SmsCode {
		smscode := cache.Rdb.Incr(cache.Ctx, "sendSms"+in.Account+"Incr").Val()
		if smscode >= 5 {
			cache.Rdb.Del(cache.Ctx, "sendSms"+in.Account+"Incr")
			cache.Rdb.Del(cache.Ctx, "sendSms"+in.Account+"login")
			logx.Error("尝试次数超过5次")
			return nil, errors.New("尝试次数超过5次")
		}
		logx.Error("短信验证码错误")
		return nil, errors.New("短信验证码错误")
	}
	cache.Rdb.Del(cache.Ctx, "sendSms"+in.Account+"Incr")
	cache.Rdb.Del(cache.Ctx, "sendSms"+in.Account+"login")
	err = h.Find(in.Account)
	if err != nil {
		h = models.User{
			Account:  in.Account,
			PassWord: in.PassWord,
		}
		err = h.Create()
		if err != nil {
			cache.Rdb.Del(cache.Ctx, "sendSms"+in.Account+"login")
			logx.Error("添加用户失败")
			return nil, err
		}
	}

	return &house.LoginResp{
		Id: int64(h.ID),
	}, nil
}
